/*
 * @Author: jerry.yjf 273950111@qq.com
 * @Date: 2025-10-21 10:05:49
 * @LastEditors: jerry.yjf 273950111@qq.com
 * @LastEditTime: 2025-10-22 17:29:56
 * @FilePath: \a1021\src\pages\login\index.jsx
 * @Description:
 *
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved.
 */
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Checkbox, Form, Input, Flex, Row, Col } from "antd";
import style from "./style.module.css";
import { useEffect, useRef, useState } from "react";
import useCount from "../../hooks/useCount";
import http from "../../utils/http";
import { useDispatch } from "react-redux";
import { setUserInfo } from "../../reducers/userInfoSlice";
import useDebounce2 from '../../hooks/useDebounce2'


//  JSON.stringify() 作用把，对象转换成字符串
// {username:123, password:123} ==>  '{"username":"123", "password":"123"}'
//  "abc" 错误的不能转
// JSON.parse() 作用把对象形式的字符串转换成真实的对象
// '{"username":"123", "password":"123"}' ===>  {username:123, password:123}
// 'abc' 错误的不能转

const Login = () => {
    const [form] = Form.useForm();
    const dis = useDispatch();

    const onFinish = useDebounce2( async (values) => {
        const res = await http.post('http://127.0.0.1:7001/login', values)
        const {code} = res.data

        if(code === 1) {
            localStorage.setItem('token', res.data.token)


            const resUserInfo = await http.get('http://127.0.0.1:7001/getUserInfo');
            const {code, data} = resUserInfo.data
            if(code === 1) {

                // 存redux
                
                dis( setUserInfo(data) )

                // 存 用户名密码
                if(values.remember) {
                    /* localStorage.setItem(
                        'userpwd', 
                        JSON.stringify( { username: values.username, password: values.password } )
                    ) */
                   localStorage.setItem('name', values.username)
                   localStorage.setItem('pwd', values.password)
                }else{
                    // localStorage.removeItem('userpwd')
                    localStorage.removeItem('name')
                   localStorage.removeItem('pwd')
                }

                // 存 RBAC权限用的用户名
                localStorage.setItem('username', values.username)

                window.location.href = '/layout/home'
            }
            
        }

    } , 800);

    useEffect(() => {
        /* const userpwd = localStorage.getItem('userpwd');
        if(userpwd) {
            const Obj = JSON.parse(userpwd);
            form.setFieldsValue(Obj)
        } */
       const name = localStorage.getItem('name');
       const pwd = localStorage.getItem('pwd');
       if(name){
         form.setFieldsValue({username: name, password: pwd})
       }
    }, [])

    // 按钮状态， 倒计时时间，  启动函数

    const {isRun, startRun, count} = useCount(10)


    return (
        <Form
            form={form}
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            autoComplete="off"
        >
            <Form.Item
                label="用户名称"
                name="username"
                rules={[
                    { required: true, message: "用户名必填!" },
                    // 只能输入字母  5 - 10 位
                    { pattern: /^[a-zA-Z]{5,10}$/, message: "用户名长度5-10位" },

                    // 任意类型的文字  5 - 10 位
                    // { pattern: /^.{5,10}$/, message: "用户名长度5-10位" },

                    // 数字的 5-10 位
                    // { pattern: /^[0-9]{5,10}$/, message: "用户名长度5-10位" },
                ]}
            >
                <Input />
            </Form.Item>

            <Form.Item
                label="密码"
                name="password"
                rules={[
                    { required: true, message: "Please input your password!" },
                    { pattern: /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[%^&*()_]).{5,10}$/, message: "用户名长度5-10位" },
                ]}
            >
                <Input.Password />
            </Form.Item>

            <Form.Item label="验证码">
                <Row gutter={8}>
                    <Col span={12}>
                        <Form.Item
                            name="captcha"
                            noStyle
                            rules={[
                                {
                                    required: true,
                                    message:
                                        "Please input the captcha you got!",
                                },
                                // 数字或字母（大小写都可以）4位
                                { pattern: /^[0-9a-zA-Z]{4}$/, message: "用户名长度5-10位" },

                            ]}
                        >
                            <Input />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Button disabled={isRun} onClick={() => {
                            startRun();
                            setTimeout(() => {
                                const code  =  Math.random().toString(32).slice(2,6)
                                form.setFieldsValue({captcha: code})
                            }, 10000)
                            
                        }}>{ isRun ? `${count}秒后重新获取`:'获取验证码'}</Button>
                    </Col>
                </Row>
            </Form.Item>

            <Form.Item name="remember" valuePropName="checked" label={null}>
                <Checkbox>记住密码</Checkbox>
            </Form.Item>

            <Form.Item shouldUpdate label={null}>
                {() => (
                <Button
                    type="primary"
                    htmlType="submit"
                    disabled={
                    !form.isFieldsTouched(['captcha', 'username', 'password'],true) ||
                    !!form.getFieldsError().filter(({ errors }) => errors.length).length
                    }
                >
                    登录
                </Button>
                )}
            </Form.Item>
        </Form>
    );
};

export default Login;
